import { Outlet, Route, RouteObject, Routes, useNavigate, useRoutes } from 'react-router-dom'
import RouterEnter from './RouterEnter'
import LayoutView from '../views/layout/LayoutView'
import LoginView from '../views/login/LoginView'
import PageError from '../views/error/PageError'
import RouterMap from './RouterMap'
import {useSelector} from "react-redux"
import { IUserStore } from '../interface/IStore'
import { useEffect } from 'react'

export default function RouterView() {
  const {user,activeKey}=useSelector((state:{user:IUserStore})=>state.user)
  const navigate=useNavigate()
  
  // console.log()
  // return (
  //   <Routes>
  //       <Route path='/' element={<RouterEnter  element={<LayoutView/>}/>}>

  //       </Route>
  //       <Route path='/login' element={<LoginView/>}/>
  //       <Route path='*' element={<PageError/>}/>
  //   </Routes>
  // )

  const routers:RouteObject[]=[
    {
      path:"/",
      element:<RouterEnter><LayoutView /></RouterEnter>,
      children:RouterMap.filter((item)=>(user.routes || []).includes(item.path))
    },
    {
      path:"/login",
      element:<LoginView/>
    },
    {
      path:"*",
      element:<PageError/>
    }
  ]
  useEffect(()=>{
    if(routerIncludes(routers,activeKey)){
      navigate(activeKey)
    }else{
      navigate("/login")
    }
  },[])

  function routerIncludes(routers:RouteObject[],path:string,bool:boolean=false){
     for(let i=0;i<routers.length;i++){
        if(routers[i].path===path) return  bool=true;
        if(routers[i].children){
          let b:boolean= routerIncludes((routers[i].children as RouteObject[]),path,bool);
          if(b) bool=b
        }
     }
     return bool;
  }
  
  return useRoutes(routers)
}
